﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Core.Helpers;
using System.Xml.Serialization;
using System.IO;
using MvcEngine.Core.Base;
using System.Reflection;

namespace MvcEngine.Core.Utils
{
    /// <summary>
    /// The utility class that can be used to serialize/deserialize objects.
    /// </summary>
    public class XmlUtil
    {
        /// <summary>
        /// Serializes the object.
        /// </summary>
        /// <param name="obj">The obj to serialize.</param>
        /// <returns>The serialized object.</returns>
        public static string SerializeObject(object obj)
        {
            Guard.ThrowIfNull(obj);

            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.Serialize(stream, obj);
                stream.Position = 0;
                StreamReader reader = new StreamReader(stream);
                return reader.ReadToEnd();
            }
        }

        /// <summary>
        /// Deserializes the object.
        /// </summary>
        /// <param name="xml">The XML to parse.</param>
        /// <param name="objType">Type of the obj.</param>
        /// <returns>The deserialized object</returns>
        public static object DeserializeObject(string xml, Type objType)
        {
            if (string.IsNullOrEmpty(xml))
                return null;

            XmlSerializer serializer = new XmlSerializer(objType);
            using (MemoryStream stream = new MemoryStream())
            {
                StreamWriter writer = new StreamWriter(stream);
                writer.Write(xml);
                writer.Flush();

                stream.Position = 0;
                return serializer.Deserialize(stream);
            }
        }
    }
}
